package com.solin.blog.web.interceptor;

import com.mysql.cj.core.util.StringUtils;
import com.solin.blog.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author solin
 * @Date 2022/1/10 11:39
 * @content
 *
 *   拦截器实现步骤
 *   1、编写一个拦截器实现 HandlerInterceptor
 *  2、编写拦截规则，preHandler 预先拦截
 *  3、拦截器注册到容器中（WebMvcConfigurer 重写addInterceptor 添加拦截规则）
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 在目标方法之前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        StringBuffer requestURL = request.getRequestURL();
        log.info("请求地址{}",requestURL);
        String token = request.getHeader("token");
        if (!StringUtils.isNullOrEmpty(token)){
            //放行  校验token的有效性
            return true;
        }
        throw new BusinessException("401","请先登录");
    }

    /**
     * 在目标发放之后执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 页面加载完成执行
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
